/*
 * Copyright 2015-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dcp.jeedcp.modules.report.web.report;

import com.alibaba.fastjson.JSON;
import com.easytoolsoft.easyreport.common.pair.IdNamePair;
import com.easytoolsoft.easyreport.engine.data.ReportMetaDataColumn;
import com.easytoolsoft.easyreport.engine.util.VelocityUtils;
import com.dcp.jeedcp.common.config.Global;
import com.dcp.jeedcp.common.persistence.Page;
import com.dcp.jeedcp.common.utils.DateUtils;
import com.dcp.jeedcp.common.utils.MyBeanUtils;
import com.dcp.jeedcp.common.utils.StringUtils;
import com.dcp.jeedcp.common.utils.excel.ExportExcel;
import com.dcp.jeedcp.common.utils.excel.ImportExcel;
import com.dcp.jeedcp.common.web.BaseController;
import com.dcp.jeedcp.common.web.JsonResult;
import com.dcp.jeedcp.modules.report.domain.QueryParameter;
import com.dcp.jeedcp.modules.report.entity.report.Report;
import com.dcp.jeedcp.modules.report.service.report.ReportService;
import com.dcp.jeedcp.modules.report.service.report.TableReportService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报表设置Controller
 * @author henry
 * @version 2017-05-12
 */
@Controller
@RequestMapping(value = "${adminPath}/report/report/report")
public class ReportController extends BaseController {

	@Autowired
	private ReportService reportService;
	@Autowired
	private TableReportService tableReportService;
	@ModelAttribute
	public Report get(@RequestParam(required=false) String id) {
		Report entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = reportService.get(id);
		}
		if (entity == null){
			entity = new Report();
		}
		return entity;
	}

	/**
	 * 报表设计页面
	 */
	@RequiresPermissions("report:report:report:index")
	@RequestMapping(value = {"index", ""})
	public String index() {
		return "modules/report/report/reportIndex";
	}
	/**
	 * 报表设置列表页面
	 */
	@RequestMapping(value = {"list", ""})
	public String list(Report report, HttpServletRequest request, HttpServletResponse response, Model model) {
//		Page<Report> page = reportService.findPage(new Page<Report>(request, response), report);
//		model.addAttribute("page", page);
		return "modules/report/report/reportList";
	}

	/**
	 * 查看，增加，编辑报表设置表单页面
	 */
	@RequiresPermissions(value={"report:report:report:view","report:report:report:add","report:report:report:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Report report, Model model) {
		model.addAttribute("report", report);
		return "modules/report/report/reportForm";
	}

	/**
	 * 保存报表设置
	 */
	@RequiresPermissions(value={"report:report:report:add","report:report:report:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Report report, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, report)){
			return form(report, model);
		}
		if(!report.getIsNewRecord()){//编辑表单保存
			Report t = reportService.get(report.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(report, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			reportService.save(t);//保存
		}else{//新增表单保存
			reportService.save(report);//保存
		}
		addMessage(redirectAttributes, "保存报表设置成功");
		return "redirect:"+Global.getAdminPath()+"/report/report/report";
	}
	//获取所有报表
	@RequestMapping(value = "/getAll")
	@RequiresPermissions("report.designer:view")
	public List<IdNamePair> getAll() {
		List<Report> reportList =reportService.findAll();
		if (CollectionUtils.isEmpty(reportList)) {
			return new ArrayList<>(0);
		}

		List<IdNamePair> list = new ArrayList<>(reportList.size());
		list.addAll(reportList.stream()
				.map(report -> new IdNamePair(String.valueOf(report.getId()), report.getName()))
				.collect(Collectors.toList()));
		return list;
	}
	/**
	 * 删除报表设置
	 */
	@RequiresPermissions("report:report:report:del")
	@RequestMapping(value = "delete")
	public String delete(Report report, RedirectAttributes redirectAttributes) {
		reportService.delete(report);
		addMessage(redirectAttributes, "删除报表设置成功");
		return "redirect:"+Global.getAdminPath()+"/report/report/report";
	}
	
	/**
	 * 批量删除报表设置
	 */
	@RequiresPermissions("report:report:report:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			reportService.delete(reportService.get(id));
		}
		addMessage(redirectAttributes, "删除报表设置成功");
		return "redirect:"+Global.getAdminPath()+"/report/report/report";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("report:report:report:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Report report, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "报表设置"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Report> page = reportService.findPage(new Page<Report>(request, response, -1), report);
    		new ExportExcel("报表设置", Report.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出报表设置记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/report/report";
    }

	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("report:report:report:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Report> list = ei.getDataList(Report.class);
			for (Report report : list){
				try{
					reportService.save(report);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条报表设置记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条报表设置记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入报表设置失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/report/report";
    }



	/**
	 * 下载导入报表设置数据模板
	 */
	@RequiresPermissions("report:report:report:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "报表设置数据导入模板.xlsx";
    		List<Report> list = Lists.newArrayList(); 
    		new ExportExcel("报表设置数据", Report.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/report/report";
    }

    //获取报表元数据列集合
	@RequestMapping(value = "/execSqlText")
//	@RequiresPermissions("report.designer:view")
	public JsonResult execSqlText(String dsId, String sqlText, Integer dataRange,
								  String queryParams, HttpServletRequest request) {
		JsonResult<List<ReportMetaDataColumn>> result = new JsonResult<>();
		if (dsId != null) {
			if (dataRange == null) {
				dataRange = 7;
			}
			sqlText = this.getSqlText(sqlText, dataRange, queryParams, request);
			result.setData(this.reportService.getMetaDataColumns(dsId, sqlText));
		} else {
			result.setSuccess(false);
			result.setMsg("没有选择数据源!");
		}
		return result;
	}

	//预览报表SQL语句
	@RequestMapping(value = "/previewSqlText")
	public JsonResult previewSqlText(String dsId, String sqlText, Integer dataRange,
									 String queryParams, HttpServletRequest request) {
		JsonResult<String> result = new JsonResult<>();
		if (dsId != null) {
			if (dataRange == null) {
				dataRange = 7;
			}
			sqlText = this.getSqlText(sqlText, dataRange, queryParams, request);
			this.reportService.explainSqlText(dsId, sqlText);
			result.setData(sqlText);
		} else {
			result.setSuccess(false);
			result.setMsg("没有选择数据源!");
		}
		return result;
	}


	@RequestMapping(value = "/getMetaColumnScheme")
	public ReportMetaDataColumn getMetaColumnScheme() {
		ReportMetaDataColumn column = new ReportMetaDataColumn();
		column.setName("expr");
		column.setType(4);
		column.setDataType("DECIMAL");
		column.setWidth(42);
		return column;
	}
	private String getSqlText(String sqlText, Integer dataRange, String queryParams,
							  HttpServletRequest request) {
		Map<String, Object> formParameters =
				tableReportService.getBuildInParameters(request.getParameterMap(), dataRange);
		if (StringUtils.isNotBlank(queryParams)) {
			List<QueryParameter> queryParameters = JSON.parseArray(queryParams, QueryParameter.class);
			queryParameters.stream()
					.filter(parameter -> !formParameters.containsKey(parameter.getName()))
					.forEach(parameter -> formParameters.put(parameter.getName(), parameter.getRealDefaultValue()));
		}
		return VelocityUtils.parse(sqlText, formParameters);
	}


}